package com.vickw.websocketdemo.handler;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * @version 1.0
 * @Description：
 * @Author VickW
 * @Date 2025/3/3 21:28
 */
public class MyWebSocketHandler extends TextWebSocketHandler {

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        // 当WebSocket连接建立时调用
        System.out.println("WebSocket连接建立: " + session.getId());
        JSONObject helloMessage = new JSONObject();
        helloMessage.put("sender", "system");
        helloMessage.put("message", "欢迎连接到WebSocket服务!");
        session.sendMessage(new TextMessage(JSON.toJSONString(helloMessage)));
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        String payload = message.getPayload();
        System.out.println("收到消息: " + payload);

        try {
            JSONObject jsonMessage = JSON.parseObject(payload);
            String sender = jsonMessage.getString("sender");
            String msgContent = jsonMessage.getString("message");

            // 处理心跳消息
            if ("system".equals(sender) && "HEARTBEAT".equals(msgContent)) {
                JSONObject heartbeatResponse = new JSONObject();
                heartbeatResponse.put("sender", "system");
                heartbeatResponse.put("message", "HEARTBEAT_RESPONSE");
                session.sendMessage(new TextMessage(heartbeatResponse.toString()));
                return;
            }

            // 处理普通消息 - 延迟5秒回复
            if ("user-a".equals(sender)) {
                // 使用线程池延迟执行回复
                ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
                executor.schedule(() -> {
                    try {
                        JSONObject response = new JSONObject();
                        response.put("sender", "user-b");
                        response.put("message", "客服回复: 已收到您的消息 - " + msgContent);
                        session.sendMessage(new TextMessage(response.toString()));
                    } catch (Exception e) {
                        System.err.println("发送延迟回复时出错: " + e.getMessage());
                    }
                }, 5, TimeUnit.SECONDS);

                // 关闭线程池（任务完成后）
                executor.shutdown();
            }
        } catch (JSONException e) {
            System.err.println("消息解析错误: " + e.getMessage());
            // 发送错误响应
            JSONObject errorResponse = new JSONObject();
            errorResponse.put("sender", "system");
            errorResponse.put("message", "错误: 消息格式不正确");
            session.sendMessage(new TextMessage(errorResponse.toString()));
        }
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, org.springframework.web.socket.CloseStatus status) throws Exception {
        // 当WebSocket连接关闭时调用
        System.out.println("WebSocket连接关闭: " + session.getId());
    }
}
